from rest_framework import viewsets, mixins
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend
from .serializers import ProductSerializers, ProductCityRelationSerializers
from .filters import ProductFilter, ProductCityFilter
from .models import Product, ProductCityRelation
from core.tools.models import Province
from core.tools.filters import ProvinceFilter
from core.tools.serializers import ProvinceSerializer


class ProductSetPagination(PageNumberPagination):
    page_size = 20
    page_size_query_param = 'limit'  # 前端可根据此参数 来动态改变每页展示的数据量
    page_query_param = "p"
    max_page_size = 100


class ProductViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    获取产品列表
    list:
        获取产品列表
    """
    queryset = Product.objects.filter(status=True)
    serializer_class = ProductSerializers
    pagination_class = ProductSetPagination
    filter_backends = (DjangoFilterBackend,)
    filter_class = ProductFilter

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        if not request.query_params.get("parent_product"):
            queryset = queryset.filter(list_show=True)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class ProductProvinceViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    产品省份列表
    list:
        获取产品省份列表
    """
    queryset = Province.objects.all()
    serializer_class = ProvinceSerializer
    filter_backends = (DjangoFilterBackend,)
    filter_class = ProvinceFilter


class ProductCityViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    产品城市列表
    list:
        获取产品省份城市列表
    """
    queryset = ProductCityRelation.objects.all()
    serializer_class = ProductCityRelationSerializers
    filter_backends = (DjangoFilterBackend,)
    filter_class = ProductCityFilter
